package com.wmf.dao;

import com.wmf.model.User;
import com.wmf.util.DataUtil;

import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class UserDao {
    public int register(User user) {
        //获取与MySQL链接的Connection对象
        Connection conn = null;
        Statement st = null;
        ResultSet rs  = null;
        PreparedStatement ptst = null;
        int res = 0;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String date = df.format(new Date());// new Date()为获取当前系统时间，也可使用当前时间戳
        try {
            String insert = "insert into user(name,phone,password,regdate) values(?,?,?,?)";

            conn = new DataUtil().getConnection();
            ptst = conn.prepareStatement(insert);
            ptst.setString(1, user.getName());
            ptst.setString(2,user.getPhone());
            ptst.setString(3, user.getPassword());
            ptst.setString(4, date);

            //执行sql语句
            ptst.execute();
            res = ptst.getUpdateCount();
            //关闭关闭ResultSet和Statement链接
            ptst.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public List<User> getUserInfo() {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        List<User> userList = new ArrayList<>();
        String getUserInfo = "select * from user";
        try {
            conn = new DataUtil().getConnection();
            stmt = conn.prepareStatement(getUserInfo);
            rs = stmt.executeQuery();
            while (rs.next()) {
                User user = new User();
                user.setName(rs.getString(1));
                user.setPhone(rs.getString(2));
                user.setPassword(rs.getString(3));
                userList.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userList;
    }
}
